import dictService from '@/api/modules/dict/dict.ts'
import { useDictStore } from '@/store/modules/dict'
import { ref, toRefs } from 'vue'

export interface DictOption {
  label: string
  value: string | number
  elTagType?: string
  elTagClass?: string
}

export interface DictApiResponse {
  dictLabel: string
  dictValue: string | number
  cssClass?: string
  listClass?: string
}

export interface UcarDictApiResponse {
  dictDataListVos: DictApiResponse[]
}

export function useUcarDict(...dictTypes: string[]) {
  const res = ref<Record<string, DictOption[]>>({})
  const dictStore = useDictStore()

  const fetchUcarDicts = async () => {
    for (const type of dictTypes) {
      res.value[type] = []

      const cached = dictStore.getDict(type)
      if (cached) {
        res.value[type] = cached
        continue
      }

      try {
        const { data } = await dictService.getUcarDicts(type)
        const dictOptions: DictOption[] = data.dictDataListVos.map((item: DictApiResponse) => ({
          label: item.dictLabel,
          value: item.dictValue,
          elTagType: item.listClass,
          elTagClass: item.cssClass,
        }))
        res.value[type] = dictOptions
        dictStore.setDict(type, dictOptions)
      }
      catch (err) {
        console.error(`Failed to fetch ucar dict: ${type}`, err)
      }
    }
  }

  fetchUcarDicts()

  return toRefs(res.value)
}
